import { Injectable, NotFoundException } from '@nestjs/common'
import { CreateBarDto, SubType } from './dto/create-bar.dto'
import { UpdateBarDto } from './dto/update-bar.dto'
import { Bar, BarDocument } from '../model/bar.schema'
import { InjectModel } from '@nestjs/mongoose'
import { Model } from 'mongoose'
import { User, UserDocument } from '../model/UserSchema.Schema'
import { SubBar, SubBarDoucment } from '../model/subBar.schema'
import { Proposition, PropositionDocument } from '../model/proposition.schema'

@Injectable()
export class BarService {
  constructor(
    @InjectModel(Bar.name) private readonly barSchema: Model<BarDocument>,
    @InjectModel(User.name) private readonly userSchema: Model<UserDocument>,
    @InjectModel(SubBar.name) private readonly subBar: Model<SubBarDoucment>,
    @InjectModel(Proposition.name) private proposition: Model<PropositionDocument>,
  ) {}
  //创建贴吧
  async create(createBarDto: CreateBarDto) {
    const result = await this.barSchema.create(createBarDto)

    const bar = await this.barSchema
      .findById({ _id: result._id }, '-__v -updatedAt')
      .orFail(new NotFoundException('not find doc'))
    return {
      data: bar,
      message: '创建成功',
      code: 200,
    }
  }

  //查找贴吧列表
  async findAll(query: { page: number; pagesize: number }, userID: string | null) {
    const { page = 1, pagesize = 10 } = query
    const result = await this.barSchema
      .find(null, '-__v -updatedAt -createdAt')
      .skip((page - 1) * pagesize)
      .limit(pagesize)
    if (!userID) {
      return {
        data: {
          result,
          count: await this.barSchema.countDocuments(),
        },
        code: 200,
        message: '查询成功',
      }
    } else {
      //已登录
      result.forEach(async (doc) => {
        const find = await this.subBar.findOne({ user: userID, bar: doc._id.toString() })
        if (find) {
          doc.isSub = true
        }
      })

      return {
        data: {
          result,
          count: await this.barSchema.countDocuments(),
        },
        code: 200,
        message: '查询成功',
      }
    }
  }

  //模糊搜索
  async likeFind(query: { page: number; pagesize: number; name: string }) {
    const { page = 1, pagesize = 10, name } = query
    const like = await this.barSchema
      .find(
        {
          barName: { $regex: name, $options: 'i' },
        },
        '-__v -updatedAt -createdAt',
      )
      .skip((page - 1) * pagesize)
      .limit(pagesize)
    if (like.length === 0) {
      return {
        data: like,
        code: 201,
        message: '什么也没有',
      }
    }

    return {
      data: {
        like,
        count: like.length,
      },
      code: 200,
      message: '搜索成功',
    }
  }

  //验证是否是该贴吧的吧主
  async verifyBarCreate(barID: string, userID: string) {
    const barInfo = await this.barSchema.findById({ _id: barID })
    const userInfo = await this.userSchema.findById({ _id: userID })

    if (barInfo.creator.toString() !== userInfo._id.toString()) {
      return false
    } else {
      return true
    }
  }

  //修改逻辑
  async update(id: string, updateBarDto: UpdateBarDto) {
    const { barLogo, barName, description } = updateBarDto
    const barInfo = await this.barSchema.findById({ _id: id })
    if (barName) {
      barInfo.barName = barName
    }
    if (barLogo) {
      barInfo.barLogo = barLogo
    }
    if (description) {
      barInfo.description = description
    }
    await barInfo.save()
    return {
      data: barInfo,
      code: 200,
      message: '修改成功',
    }
  }

  //删除贴吧
  async remove(id: string) {
    // const result = await this.barSchema.findByIdAndDelete({ _id: id })
    const find = await this.barSchema.findById(id).orFail(new NotFoundException('not find'))
    const result = await find.remove()
    //删除贴吧内的所有帖子
    // const deleteProposition = await this.proposition.deleteMany({ bar: id })
    //删除评论
    return {
      data: result,
      code: 200,
      message: '删除成功',
    }
  }

  /* 关注贴吧 */
  async sub(info: SubType) {
    let isSub = false
    const find = await this.subBar.findOne({ bar: info.bar })
    console.log(find)

    const barinfo = await this.barSchema.findById(info.bar).orFail(new NotFoundException('Not find!'))

    if (find) {
      //表示已经关注 此时取消关注
      await this.subBar.findByIdAndDelete(find._id)
      //减少关注数
      if (barinfo.beSubCount > 0) {
        barinfo.beSubCount--
        await barinfo.save()
      }
      isSub = false
      return {
        data: { isSub },
        code: 200,
        message: '取消关注成功',
      }
    } else {
      //表示为关注 该状态为关注
      isSub = true
      const back = await this.subBar.create({ user: info.user, bar: info.bar })
      const result = await this.subBar
        .findById({ _id: back._id }, '-__v -updatedAt -createdAt')
        .populate('user', 'username photo')
        .populate('bar', 'barName barLogo')
        .orFail(new NotFoundException('Not find!'))
      barinfo.beSubCount++
      await barinfo.save()
      return {
        data: { result, isSub },
        code: 200,
        message: '关注成功',
      }
    }
  }

  /* 获取贴吧详情 */
  async getBarMsg(barID: string, userID: string | null = null) {
    const back = await this.barSchema.findById(barID, '-__v -updatedAt')
    let isSub = false
    if (userID) {
      const sub = await this.subBar.findOne({ user: userID, bar: barID })
      if (sub) {
        //用户已关注该贴吧
        isSub = true
        return {
          data: { bar: back, isSub },
          code: 200,
          message: '获取成功',
        }
      } else {
        //用户未关注
        isSub = false
        return {
          data: { bar: back, isSub },
          code: 200,
          message: '获取成功',
        }
      }
    } else if (!userID) {
      //用户未登录
      isSub = false
      return {
        data: { bar: back, isSub },
        code: 200,
        message: '获取成功',
      }
    }
  }
}
